import { create } from "zustand";
import { persist, devtools } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import { AppListItem, AppListReq, CreateAppReq, GetWorkBenhList } from "@/common/types";
import appService from "@/api/services/appService";
import { useMutation } from "@tanstack/react-query";
import { Result } from "@/types/api";

type State = {
  sketchApps: AppListItem[];
  sketchAppsTotal: number;
  myApps: AppListItem[];
  myAppsTotal: number;
  publicDataList: Array<GetWorkBenhList>;
  marketDataList: Array<GetWorkBenhList>;
};

type Action = {
  loadAllSketchApps: (data: AppListReq) => any;
  loadMyApps: (data: AppListReq) => any;
  createApp: (data: CreateAppReq) => any;
  getPublicDataList: (data: Array<GetWorkBenhList>) => any;
  getMarketDataList: (data: Array<GetWorkBenhList>) => any;
}

export const useAppStore = create<State & Action>()(
  persist(
    immer((set, get) => ({
      sketchApps: [],
      sketchAppsTotal: 0,
      myApps: [],
      myAppsTotal: 0,
      publicDataList: [],
      marketDataList: [],
      getPublicDataList: (data: Array<GetWorkBenhList>) => {
        set(state => {
          state.publicDataList = data
        })
      },
      getMarketDataList: (data: Array<GetWorkBenhList>) => {
        set(state => {
          state.marketDataList = data
        })
      },
      loadAllSketchApps: async (req: AppListReq) => {
        const response = await appService.appList({ ...req, type: 'public' });
        const data = await response;
        set(state => {
          state.sketchApps = data.list;
          state.sketchAppsTotal = data.total;
        });
        return response;
      },
      loadMyApps: async (req: AppListReq) => {
        const response = await appService.appList({ ...req, type: '' });
        const data = await response;
        set(state => {
          state.myApps = data.list;
          state.myAppsTotal = data.total;
        });
        return response;
      },
      createApp: async (req: CreateAppReq) => {
        const response = await appService.createApp(req);
        return response;
      }
    })),
    {
      name: 'appStore',
      version: 1,
      partialize: (state) => ({})
    }
  )
)

